//(c) Copyright 2016 SuperMap. All Rights Reserved. 
//2016-04-18
var map, baseLayer, drawPoint, drawLine, drawPolygon, Geojson, drawType;
var pt = [];

var style = {
	strokeColor: "#304DBE",
	strokeWidth: 1
}
var pstyle = {
	fillColor: "#339933",
	fillOpacity: 1,
	strokeOpacity: 0,
	pointRadius: 1
};
var init = function() {
	//alert("aaa");
	var resolutions = [9783.93962049996, 4891.96981024998, 2445.98490512499, 1222.992452562495, 611.4962262813797, 305.74811314055756, 152.87405657041106, 76.43702828507324, 38.21851414253662, 19.10925707126831, 9.554628535634155, 4.77731426794937, 2.388657133974685];
	var matrixIds = new Array(13);
	for (var i = 0; i < 13; i++) {
		matrixIds[i] = {
			identifier: i
		};
	};
	//初始化地图拖拽控件类
	dragPan = new SuperMap.Control.DragPan();
	//当该属性为true，拖拽地图时，鼠标移动到地图可视区域外依然有效。默认为false
	dragPan.documentDrag = true;
	//设置是否使用拖拽动画。默认为false，不使用动画
	dragPan.enableKinetic = true;
	//执行动画的间隔，默认为10，单位是毫秒
	dragPan.kineticInterval = 20;

	//矢量图层
	vectorLayer = new SuperMap.Layer.Vector("vectorLayer");
	//创建捕捉对象，第一个参数指的是需要进行捕捉的要素图层，后面两个参数分别是点要素和线要素的捕捉容限，第四个参数是附加参数
	snap01 = new SuperMap.Snap([vectorLayer], 10, 10, {
		actived: true
	});
	//矢量要素编辑控件
	modifyFeature = new SuperMap.Control.ModifyFeature(vectorLayer);
	modifyFeature.snap = snap01;

	//画点
	drawPoint = new SuperMap.Control.DrawFeature(vectorLayer, SuperMap.Handler.Point, {
		multi: true
	});
	drawPoint.events.on({
		"featureadded": drawCompleted
	});
	//画直线
	drawLine = new SuperMap.Control.DrawFeature(vectorLayer, SuperMap.Handler.Path, {
		multi: false
	});
	drawLine.events.on({
		"featureadded": drawCompleted
	});
	//画面
	drawPolygon = new SuperMap.Control.DrawFeature(vectorLayer, SuperMap.Handler.Polygon);
	drawPolygon.events.on({
		"featureadded": drawCompleted
	});

	dragFeature = new SuperMap.Control.DragFeature(vectorLayer);
	//实例化地图
	map = new SuperMap.Map("map", {
		controls: [
			dragPan,
			new SuperMap.Control.ScaleLine({
				isImperialUnits: false
			}),
			new SuperMap.Control.Zoom(),
			new SuperMap.Control.LayerSwitcher(),
			new SuperMap.Control.OverviewMap(),
			new SuperMap.Control.Navigation({
				
			}), dragFeature, drawPoint, drawLine, drawPolygon, modifyFeature
		],
		maxExtent: new SuperMap.Bounds(8176078.237500001, 379653.95419999957, 15039542.061499998, 7087813.645199999)
	});

	//底图图层
	baseLayer = new SuperMap.Layer.WMTS({
		name: "Maps_StreetMap",
		url: "http://172.24.186.81:6080/arcgis/rest/services/Maps/StreetMap/MapServer/wmts",
		layer: "Maps_StreetMap",
		style: "default",
		matrixIds: matrixIds,
		matrixSet: "default028mm",
		format: "image/jpg",
		resolutions: resolutions, //分辨率数组
		tileOrigin: new SuperMap.LonLat(-20037508.342787, 20037508.342787), //瓦片矩阵左上角
		requestEncoding: "KVP"
	});
	map.addLayers([baseLayer, vectorLayer]);
	map.events.on({
		"click": cbMapClick
	}); //添加click事件

	map.setCenter(new SuperMap.LonLat(11997336, 3544032), "4");
}

function draw_point() {
	deactiveAll();
	vectorLayer.removeAllFeatures();
	drawPoint.activate();
}

function dragPanDeactivated() {
	dragPan.deactivate();
	alert("取消激活DragPan");
}

function dragPanActivated() {
	dragPan.activate();
	alert("激活DragPan");
}

function draw_line() {
	deactiveAll();
	vectorLayer.removeAllFeatures();
	drawLine.activate();
}

function draw_polygon() {
	deactiveAll();
	vectorLayer.removeAllFeatures();
	drawPolygon.activate();
}
//几何对象线环类
function draw_linearRing(pt) {
	drawType = "linearRing";
	deactiveAll();
	vectorLayer.removeAllFeatures();
}

var po = function() {
		po.prototype.x = 0;
		po.prototype.y = 0;
	}
	//解析GeoJSON串,更改点坐标经纬度  WebMercator  -- lonLat
function change2LonLat(geojson) {
	var obj = jQuery.parseJSON(geojson);
	var coorArray = obj.geometry.coordinates[0];
	for (var i = 0; i < coorArray.length; i++) {
		var point = new po();
		point.x = coorArray[i][0];
		point.y = coorArray[i][1];
		var m = WebMercator2lonLat(point);
		coorArray[i][0] = m.x;
		coorArray[i][1] = m.y;
	}
	obj.geometry.coordinates[0] = coorArray;
	return JSON.stringify(obj);
}

function change2WebMercator(geojson) {
	var obj = geojson;
	for (var j = 0; j < obj.featureCollection.features.length; j++) {
		var coorArray = obj.featureCollection.features[j].geometry.coordinates[0];
		for (var i = 0; i < coorArray.length; i++) {
			var point = new po();
			point.x = coorArray[i][0];
			point.y = coorArray[i][1];
			var m = lonLat2WebMercator(point);
			coorArray[i][0] = m.x;
			coorArray[i][1] = m.y;
		}
	}
	return JSON.stringify(obj);
}
//经纬度转Web墨卡托  
function lonLat2WebMercator(lonLat) {
	var mercator = new po();
	var x = lonLat.x * 20037508.34 / 180;
	var y = Math.log(Math.tan((90 + lonLat.y) * Math.PI / 360)) / (Math.PI / 180);
	y = y * 20037508.34 / 180;
	mercator.x = x;
	mercator.y = y;
	return mercator;
}
//Web墨卡托转经纬度  
function WebMercator2lonLat(mercator) {
	var lonLat = new po();
	var x = mercator.x / 20037508.34 * 180;
	var y = mercator.y / 20037508.34 * 180;
	y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);
	lonLat.x = x;
	lonLat.y = y;
	return lonLat;
}

function cbMapClick(e) {
	if (drawType == "linearRing") {
		var px = new SuperMap.Geometry.Point(map.getLonLatFromPixel(e.xy).lon, map.getLonLatFromPixel(e.xy).lat);
		pt.push(px);
		if (pt.length > 1) {
			for (var i = 0; i + 1 <= pt.length - 1; i++) {
				var pL = [];
				pL.push(pt[i], pt[i + 1]);
				var line = new SuperMap.Geometry.LineString(pL);
				var linevector = new SuperMap.Feature.Vector(line);

				linevector.style = {
					strokeColor: "#7B68EE",
					strokeWidth: 2
				};
				vectorLayer.addFeatures([linevector]);
			}
		}
	}
}
var geolinedata, georegiondata;

//异步请求
function getAjaxJson(type) {
	var ajaxjson;
	$.ajax({
		type: "get",
		async: false,
		url: "http://172.24.176.171/productService/temp/" + type,
		//url: "http://localhost:8080/productService/temp/" + type,
		dataType: "jsonp",
		jsonp: "jsoncallback", //这里为后台返回的动态函数
		success: function(data) {
			switch (type) {
				case "grib":
					ajaxjson = featuredata(data);
					GribDataLoaded(ajaxjson);
					break;
				case "geoline":
					ajaxjson = change2WebMercator(data);
					GeoLineDataLoaded(ajaxjson);
					break;
				case "georegion":
					ajaxjson = change2WebMercator(data);
					GeoRegionDataLoaded(ajaxjson);
					break;
				default:
					console.log("未能匹配到该Ajax类型请求!")
					break;
			}
		},
		error: function(XHR, textStatus, errorThrown) {
			alert("请求出错(请检查相关度网络状况.)");
		}
	}); //end ajax
}

//生成渲染图
var maptype = "";

function featuredata(obj) {
	for (var j = 0; j < obj.length; j++) {
		var point = new po();
		point.x = obj[j][0];
		point.y = obj[j][1];
		var m = lonLat2WebMercator(point);
		obj[j][0] = m.x;
		obj[j][1] = m.y;
	}
	return obj;
}

//ajax请求数据成功返回后执行，加载图层到地图
function GribDataLoaded(obj) {
	var features = [];
	//新建一个策略并使用在矢量要素图层(vector)上。 
	var strategy = new SuperMap.Strategy.GeoText();
	strategy.style = {
		fontColor: "#000",
		fontSize: "10px",
	};
	for (var i = 0; i < obj.length; i++) {
		//var val = obj[i][2] == ""?0:obj[i][2];
		//parseInt()
		var geoText = new SuperMap.Geometry.GeoText(obj[i][0], obj[i][1], obj[i][2]);
		var geotextFeature = new SuperMap.Feature.Vector(geoText);
		features.push(geotextFeature);
	}
	if (map.getBy("layers", "name", "Label").length != 0) {
		map.removeLayer(map.getBy("layers", "name", "Label")[0], false);
	}

	var gridLayer = new SuperMap.Layer.Vector("Label", {
		strategies: [strategy]
	});
	map.addLayers([gridLayer]);
	gridLayer.addFeatures(features);
}

function GeoLineDataLoaded(obj) {
	var vectorSource = new SuperMap.Feature.Vector({
		features: new SuperMap.Format.GeoJSON().read(jQuery.parseJSON(obj).featureCollection)
	});
	maptype = "defaultMap";
	if (map.getBy("layers", "name", "GeoLine").length != 0) {
		map.removeLayer(map.getBy("layers", "name", "GeoLine")[0], false);
	}
	var GeoLineLayer = new SuperMap.Layer.Vector("GeoLine");
	map.addLayers([GeoLineLayer]);
	for (var i = 0; i < vectorSource.geometry.features.length; i++) {
		vectorSource.geometry.features[i].style = getCoutourStyle(vectorSource.geometry.features[i].data.dValue, maptype);
		GeoLineLayer.addFeatures(vectorSource.geometry.features[i]);
	}
}

function GeoRegionDataLoaded(obj) {
	var vectorSource = new SuperMap.Feature.Vector({
		features: new SuperMap.Format.GeoJSON().read(jQuery.parseJSON(obj).featureCollection)
	});
	maptype = "defaultMap";

	if (map.getBy("layers", "name", "GeoRegion").length != 0) {
		map.removeLayer(map.getBy("layers", "name", "GeoRegion")[0], false);
	}
	var GeoRegionLayer = new SuperMap.Layer.Vector("GeoRegion");
	map.addLayers([GeoRegionLayer]);
	for (var i = 0; i < vectorSource.geometry.features.length; i++) {
		vectorSource.geometry.features[i].style = getPolygonStyle(vectorSource.geometry.features[i].data.dValue, maptype);

		GeoRegionLayer.addFeatures(vectorSource.geometry.features[i]);
	}
	//addLegend(maptype, jQuery.parseJSON(Jsondata).legend, '图例');
	//addMaptitle(Ext.Date.format(mDataDate, 'Y-m-d') + '广东' + mCrop + '发育期' + mMapType);
}

//发起Ajax请求，响应button事件
function createGribLayer() {
	getAjaxJson("grib");
}

function createGeoLineLayer() {
	getAjaxJson("geoline");
}

function createGeoRegionLayer() {
	getAjaxJson("georegion");
}

//等值面填充样式
function getPolygonStyle(dValue, maptype) {
	var style = new SuperMap.Style();
	switch (maptype) {
		case "defaultMap":
			switch (dValue) {
				case "0.0":
					style = {
						fillColor: "#0000FF",
						fillOpacity: 0.2
					}
					break;
				case "1.0":
					style = {
						fillColor: "#0096FF",
						fillOpacity: 0.2
					}
					break;
				case "2.0":
					style = {
						fillColor: "#00FFFF",
						fillOpacity: 0.2
					}
					break;
				case "3.0":
					style = {
						fillColor: "#C8FF96",
						fillOpacity: 0.2

					}
					break;
				case "4.0":
					style = {
						fillColor: "#FFFF96",
						fillOpacity: 0.2
					}
					break;
				case "5.0":
					style = {
						fillColor: "#FFFF32",
						fillOpacity: 0.2
					}
					break;
				case "6.0":
					style = {
						fillColor: "#FF9664",
						fillOpacity: 0.2
					}
					break;
				case "7.0":
					style = {
						fillColor: "#FF6464",
						fillOpacity: 0.2
					}
					break;
				case "8.0":
					style = {
						fillColor: "#FF0000",
						fillOpacity: 0.2
					}
					break;
				case "9.0":
					style = {
						fillColor: "#EAEC1F",
						fillOpacity: 0.3
					}
					break;
				case "10.0":
					style = {
						fillColor: "#EAA371",
						fillOpacity: 0.3
					}
					break;
				case "11.0":
					style = {
						fillColor: "#EA291F",
						fillOpacity: 0.3
					}
					break;
				default:
					console.log("设置等值面填充样式，进入switch默认");
					style = {
						fillOpacity: 0
					}
					console.log("default")
					break;
			}
			break;
		default:
			console.log("设置maptype类型时，进入switch默认");
			break;

	}
	return style;
}
//设置等值线样式
function getCoutourStyle(dValue, maptype) {
	var style = new SuperMap.Style();
	switch (maptype) {
		case "defaultMap":
			switch (dValue) {
				case "0.0":
					style = {
						strokeColor: "#0000FF",
						strokeOpacity: 1,
						strokeWidth: 1
					}
					break;
				case "1.0":
					style = {
						strokeColor: "#0096FF",
						strokeOpacity: 1,
						strokeWidth: 1
					}
					break;
				case "2.0":
					style = {
						strokeColor: "#BC1717",
						strokeOpacity: 1,
						strokeWidth: 1
					}
					break;
				case "3.0":
					style = {
						strokeColor: "#FF1CAE",
						strokeOpacity: 1,
						strokeWidth: 1
					}
					break;
				case "4.0":
					style = {
						strokeColor: "#FF1CAE",
						strokeOpacity: 1,
						strokeWidth: 1
					}
					break;
				case "5.0":
					style = {
						strokeColor: "#BC1717",
						strokeOpacity: 1,
						strokeWidth: 1
					}
					break;
				case "6.0":
					style = {
						strokeColor: "#FF9664",
						strokeOpacity: 1,
						strokeWidth: 1
					}
					break;
				case "7.0":
					style = {
						strokeColor: "#FF6464",
						strokeOpacity: 1,
						strokeWidth: 1
					}
					break;
				case "8.0":
					style = {
						strokeColor: "#FF0000",
						strokeOpacity: 1,
						strokeWidth: 1
					}
					break;
				case "9.0":
					style = {
						strokeColor: "#EAEC1F",
						strokeOpacity: 1,
						strokeWidth: 1
					}
					break;
				default:
					console.log("设置等值面填充样式，进入switch默认");
					break;
			}
			break;
		default:
			console.log("设置maptype类型时，进入switch默认");
			break;
	}
	return style;
}

function addLegend(maptype, legendinfo, headtext) {

}

function addTitle(headtext) {

}
//$(document).ready(function() {
//	$(document).bind("contextmenu", function(e) {
//		return false;
//	});
//});

//函数的参数x,y为椭圆中心；a,b分别为椭圆横半轴
function createEllipse(x, y, a, b) {
	var step = (a > b) ? 1 / a : 1 / b,
		points = [];
	//step是等于1除以长轴值a和b中的较大者
	//i每次循环增加1/step，表示度数的增加
	//这样可以使得每次循环所绘制的路径（弧线）接近1像素
	for (var i = 0; i < 2 * Math.PI; i += step) {
		//参数方程为x = a * cos(i), y = b * sin(i)，
		//参数为i，表示度数（弧度）
		var point = new SuperMap.Geometry.Point(x + a * Math.cos(i), y + b * Math.sin(i));
		points.push(point);
	}
	return points;
}
//圆
function createCircle(origin, radius, sides, r, angel) {
	var rR = r * Math.PI / (180 * sides);
	var rotatedAngle, x, y;
	var points = [];
	for (var i = 0; i < sides; ++i) {
		rotatedAngle = rR * i;
		x = origin.x + (radius * Math.cos(rotatedAngle));
		y = origin.y + (radius * Math.sin(rotatedAngle));
		points.push(new SuperMap.Geometry.Point(x, y));
	}
	rotatedAngle = r * Math.PI / 180;
	x = origin.x + (radius * Math.cos(rotatedAngle));
	y = origin.y + (radius * Math.sin(rotatedAngle));
	points.push(new SuperMap.Geometry.Point(x, y));
	var ring = new SuperMap.Geometry.LinearRing(points);
	ring.rotate(parseFloat(angel), origin);
	var geo = new SuperMap.Geometry.Collection([ring]);
	geo.origin = origin;
	geo.radius = radius;
	geo.r = r;
	geo.angel = angel;
	geo.sides = sides;
	geo.polygonType = "Curve";
	return geo;
}
//定义 drawCompleted 函数，触发 featureadded 事件会调用此函数 
//事件参数 eventArgs 包含了绘制的要素 feature 信息 {feature: featureObj} 
function drawCompleted(eventArgs) {
	deactiveAll();
	//实例化一个GeoJson解释器
	var geojson = new SuperMap.Format.GeoJSON();
	// 获取传入参数 eventArgs 的几何信息 ,转换为geojson格式
	Geojson = geojson.write(eventArgs.feature);
	Geojson = change2LonLat(Geojson);
}
//编辑要素
function editfeature() {
	deactiveAll();
	modifyFeature.activate();
	snap01.on();
	snapState = true;
}
//激活拖拽要素控件
function dragFeature() {
	dragFeature.activate();
}

function deactiveAll() {
	dragPan.activate();
	drawPoint.deactivate();
	drawLine.deactivate();
	drawPolygon.deactivate();
	modifyFeature.deactivate();
	dragFeature.deactivate();
}

function clearFeatures() {
	deactiveAll();
	vectorLayer.removeAllFeatures();
}

function readJson() {
	//创建一个GeoJSON解析器
	var geojsonParse = new SuperMap.Format.GeoJSON();
	//将GeoJSON对象转化成要素数组
	var features = geojsonParse.read(Geojson);
	//最后将要素数组加到矢量图层里面进行渲染

	//var features[] = vlayer.features;  
	for (var i = 0; i < features.length; i++) {
		var geom = features[i].geometry;
		var lonlats = geom.getVertices();
		alert(lonlats);
	};
}

function initBtnClick() {
	$(".btn-day").each(function(index) {
		$(this).click(function() {
			$(this).css("background-color", "green");
		});
	});
	$(".btn-element").each(function(index) {
		$(this).click(function() {
			$(this).css("background-color", "green");
		});
	});
	$(".btn-product").each(function(index) {
		$(this).click(function() {
			$(this).css("background-color", "green");
		});
	});
	$(".btn-p-area").each(function(index) {
		$(this).click(function() {
			$(this).css("background-color", "green");
			var lonlat;
			switch (index) {
				case 0:
					lonlat = new SuperMap.LonLat(11861091.742372222, 3448396.2383977077);
					break;
				case 1:
					lonlat = new SuperMap.LonLat(11861091.742372222, 3448396.2383977077);
					break;
				case 2:
					lonlat = new SuperMap.LonLat(11955713.309533333, 3467608.989931638);
					break;
				case 3:
					lonlat = new SuperMap.LonLat(12067032.800311113, 3609394.7137283715);
					break;
				case 4:
					lonlat = new SuperMap.LonLat(11994675.131305555, 3417715.06318066);
					break;
				case 5:
					lonlat = new SuperMap.LonLat(12108221.011898888, 3443277.6632521753);
					break;
				default:
					break;
			}
			map.setCenter(lonlat, 7, true, false);
		});
	});
	$(".btn-s-area").each(function(index) {
		$(this).click(function() {
			$(this).css("background-color", "green");
			var lonlat;
			switch (index) {
				case 0:
					lonlat = new SuperMap.LonLat(11861091.742372222, 3448396.2383977077);
					break;
				case 1:
					lonlat = new SuperMap.LonLat(11863318.132187776, 3445836.6975907465);
					break;
				case 2:
					lonlat = new SuperMap.LonLat(11863318.132187776, 3452236.5003576134);
					break;
				case 3:
					lonlat = new SuperMap.LonLat(11849959.793294445, 3443277.6632521753);
					break;
				case 4:
					lonlat = new SuperMap.LonLat(11855525.767833333, 3439440.0602524863);
					break;
				case 5:
					lonlat = new SuperMap.LonLat(11863318.132187776, 3441998.3358484935);
					break;
				case 6:
					lonlat = new SuperMap.LonLat(11853299.378017778, 3436882.289845464);
					break;
				case 7:
					lonlat = new SuperMap.LonLat(11844393.818755556, 3477867.526222703);
					break;
				case 8:
					lonlat = new SuperMap.LonLat(11857752.157648887, 3424100.9977744306);
					break;
				case 9:
					lonlat = new SuperMap.LonLat(11869997.301634444, 3467608.989931638);
					break;
				case 10:
					lonlat = new SuperMap.LonLat(11872223.691450002, 3379464.9166168314);
					break;
				case 11:
					lonlat = new SuperMap.LonLat(12067032.800311113, 3609394.7137283715);
					break;
				case 12:
					lonlat = new SuperMap.LonLat(11955713.309533333, 3467608.989931638);
					break;
				case 13:
					lonlat = new SuperMap.LonLat(12108221.011898888, 3443277.6632521753);
					break;
				case 14:
					lonlat = new SuperMap.LonLat(11920091.072484445, 3486850.476238509);
					break;
				case 15:
					lonlat = new SuperMap.LonLat(11816563.946061112, 3397301.0695377258);
					break;
				case 16:
					lonlat = new SuperMap.LonLat(11831405.951127531,3500808.493458314);
					break;
				case 17:
					lonlat = new SuperMap.LonLat(11792473.183742402, 3421795.058376108);
					break;
				case 18:
					lonlat = new SuperMap.LonLat(11922934.728876363, 3396479.946194382);
					break;
				case 19:
					lonlat = new SuperMap.LonLat(11768696.565026667, 3465045.634245877);
					break;
				default:
					break;
			}
			map.setCenter(lonlat, 7, true, false);
		});
	});
//	$(".btn-menu").each(function(index) {
//		$(this).click(function() {
//			$(this).css("background-color", "");
//		});
//	});
}

function dateMove() {
	$("#pre").click(function(index) {
		//前面添加
		//$("#datetime a:first").clone(true).prependTo($("#datetime"));
		
		//后面删除
		$("#datetime a:last-child").remove();
	})	
	$("#next").click(function(index) {
		//前面删除
		$("#datetime a:first").remove();
		//后面添加
		$("#datetime").append($("#datetime a:last-child").clone());
	})
}

//经纬度转Web墨卡托  
function temp(a, b) {
	var mercator = new po();
	var x = a * 20037508.34 / 180;
	var y = Math.log(Math.tan((90 + b) * Math.PI / 360)) / (Math.PI / 180);
	y = y * 20037508.34 / 180;
	mercator.x = x;
	mercator.y = y;
	return mercator;
}
initBtnClick();